#! /usr/bin/env python
# -*-coding:utf-8-*-
__author__ = 'jenking'

from hashlib import md5
import requests
import os, datetime
import time
import json

class GulpModules(object):

    def __init__(self,host, project, version, path, headers):
        self.host=host
        self.project_name = project
        self.zip = ""
        self.size = ""
        self.modify_time = ""
        self.md5 = ""
        self.filelist = []
        self.notify = True
        self.response = None
        self.basepath = path
        self.headers = headers
        self.version = version
        self.fileStatus = []

    def chgVerName(self, value):
        _temp_str = str(value)
        if len(_temp_str)==3:
            _temp_str=_temp_str+"0"
        newStr = _temp_str[0:-1] + "." + _temp_str[-1:]
        return newStr

    def md5_file(self, name):
        m = md5()
        a_file = open(name, "rb")
        m.update(a_file.read())
        a_file.close()
        return m.hexdigest()

    def read_file(self):

        list = os.listdir(self.basepath)

        for i in range(0, len(list)):
            path = os.path.join(self.basepath, list[i])
            if os.path.isfile(path):
                self.filelist.append(list[i])

        for i in range(0, len(self.filelist)):
            path = os.path.join(self.basepath, self.filelist[i])
            if os.path.isdir(path):
                continue

            self.timestamp = os.path.getmtime(path)
            ts1 = os.stat(path).st_mtime

            date = datetime.datetime.fromtimestamp(self.timestamp)
            zip = list[i]
            version = self.version
            md5 = self.md5_file(path)
            size = os.path.getsize(path) / 1024
            module_path=self.basepath
            module_type = "dev" if zip.startswith("dev") else "min"
            project_url=self.host+"/"+self.project_name+"/bin/"

            template = "项目名:{project}\n版本号:{version}\n文件名:{zip}\n包类型:{module_type}\n大小:{size}KB\n修改时间:{modify_time}\nMD5:{md5}\n路径:{module_path}\n".format(
                project=self.project_name,
                version=self.chgVerName(self.version),
                zip=zip,
                module_type=module_type,
                size=size,
                modify_time=date.strftime('%Y-%m-%d %H:%M:%S'),
                md5=md5,
                module_path=module_path
            )

            print template

            file_info = {
                "project": self.project_name,
                "version": version,
                "zip": zip,
                "module_type": module_type,
                "module_path":module_path,
                "size": size,
                "modify_time": date,
                "md5": md5,
                "notify":self.notify,
                "project_url":project_url
            }
            self.fileStatus.append(file_info)

    def postInfo(self):
        baseurl=self.host+"/django/home/chgmodinfo/"+self.project_name+"/"
        t=time.time()
        for mod in self.fileStatus:
            if mod["module_type"]=="dev":
                url=baseurl+mod["version"]+"/dev/"
            else:
                url=baseurl+mod["version"]+"/min/"

            r=requests.post(url,data=mod,headers=headers)
            if (r.status_code == requests.codes.ok):
                content=r.text
                print content

        print "Total run time:",time.time()-t

    def run(self):
        self.read_file()
        self.postInfo()

headers = {
    'content-type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36',
    'Accept': 'text/plain',
}

f=file("package.json")
packageData = json.load(f)

project_name = packageData["project"]
version= packageData["version"][0:-2]+packageData["version"][-1:]
host=packageData["host"]
path =packageData["path"]

gulpMod = GulpModules(host,project_name, version, path, headers)
gulpMod.run()
